#!/bin/sh
"""": # -*-python-*-
bup_exec="$(dirname "$0")/bup-exec" || exit $?
exec "$bup_exec" "$0" ${1+"$@"}
"""

from __future__ import absolute_import, print_function
import os, stat, sys

from bup.compat import get_argvb
from bup.io import byte_stream


# Print the full paths of all the files in each hardlink set
# underneath one of the paths.  Separate sets with a blank line, sort
# the paths within each set, and sort the sets by their first path.

def usage():
    print("Usage: hardlink-sets <paths ...>", file=sys.stderr)

argvb = get_argvb()

if len(argvb) < 2:
    usage()
    sys.exit(1)

def on_walk_error(e):
    raise e

sys.stdout.flush()
out = byte_stream(sys.stdout)

hardlink_set = {}

for p in argvb[1:]:
  for root, dirs, files in os.walk(p, onerror = on_walk_error):
      for filename in files:
          full_path = os.path.join(root, filename)
          st = os.lstat(full_path)
          if not stat.S_ISDIR(st.st_mode):
              node = b'%d:%d' % (st.st_dev, st.st_ino)
              link_paths = hardlink_set.get(node)
              if link_paths:
                  link_paths.append(full_path)
              else:
                  hardlink_set[node] = [full_path]

# Sort the link sets.
for node, link_paths in hardlink_set.items():
    link_paths.sort()

first_set = True
for link_paths in sorted(hardlink_set.values(), key = lambda x : x[0]):
    if len(link_paths) > 1:
        if first_set:
            first_set = False
        else:
            out.write(b'\n')
        for p in sorted(link_paths):
            out.write(p + b'\n')

sys.exit(0)
